package com.wwg.springboard;

import android.text.TextUtils;

import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

public class UserActionHistoryProxy {
    private static final String INSERT = "添加";
    private static final String DELETE = "删除";

    private volatile static UserActionHistoryProxy sInstance;
    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
            "HH:mm:ss.SSS",
            Locale.getDefault()
    );

    private StringBuilder sb = new StringBuilder();
    private UserActionHistoryProxy() {
    }

    public static UserActionHistoryProxy getInstance() {
        if (sInstance == null) {
            synchronized (UserActionHistoryProxy.class) {
                if (sInstance == null) {
                    sInstance = new UserActionHistoryProxy();
                }
            }
        }

        return sInstance;
    }

    String getCurrentTime() {
        long time = System.currentTimeMillis();
        return simpleDateFormat.format(new Date(time));
    }

    public void insert(String host, String name, int index) {
        appendSb(host, INSERT, name, index);
    }

    public void delete(String host, String name, int index) {
        appendSb(host, DELETE, name, index);
    }

    public List<String> getRecord() {
        List<String> result = new LinkedList<>();

        LineNumberReader reader = new LineNumberReader(new StringReader(sb.toString()));
        try {
            String line = reader.readLine();
            while (line != null) {
                result.add(line);
                line = reader.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    void appendSb(String host, String action, String name, int index) {
        sb.append(host);
        sb.append(" ");
        sb.append(getCurrentTime());
        sb.append(" ");
        sb.append(action);
        sb.append(" ");
        sb.append(name);
        sb.append(" ");
        sb.append(String.valueOf(index));
        sb.append("\n");
    }

    public void clear() {
        sb = new StringBuilder();
    }

}
